package com.rush.springbootinit.aop;

import com.rush.springbootinit.annotation.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Slf4j
@Aspect
@Component
public class DistributedLockAspect {
    @Resource
    private RedissonClient redissonClient;
    @Around("@annotation(distributedLock)")
    public Object around(ProceedingJoinPoint point , DistributedLock distributedLock){
        log.info("获取锁：" + distributedLock.key());
        String key = distributedLock.key();
        long waitTime = distributedLock.waitTime();
        long leaseTime = distributedLock.leaseTime();
        TimeUnit timeUnit = distributedLock.timeUnit();
        RLock lock = redissonClient.getLock(key);
        Boolean acquired = false;
        try {
            // 尝试获取锁
            acquired = lock.tryLock(waitTime, leaseTime, timeUnit);
            if (acquired){
                //获取锁成功，执行目标方法
                return point.proceed();
            }else {
                //获取锁失败，抛异常
                throw new RuntimeException("不能获取锁：" + key);
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            if (acquired){
                //释放锁
                lock.unlock();
            }
        }
    }
}
